﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using ProjectManageSystemApi.Models;
using ProjectManageSystemApi.Services;
using ProjectManageSystemApi.Utilities;
using System;

namespace ProjectManageSystemApi.Controllers
{
    /// <summary>
    /// 考勤接口
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    [ApiExplorerSettings(GroupName = Grouping.GroupName_v1)]
    [Authorize]
    public class UserCheckInfoController : Controller
    {
        readonly IUserCheckInfoService _userCheckInfo;
        readonly IUserServices _user;
        readonly Config _config;
        public UserCheckInfoController(IUserCheckInfoService userCheckInfo, IUserServices user, Config config)
        {
            _userCheckInfo = userCheckInfo;
            _user = user;
            _config = config;
        }

        /// <summary>
        ///  打上班卡api
        /// </summary>
        [HttpPost]
        [Route("UserClockIn")]
        public ApiResult UserClockIn([FromHeader(Name = "Authorization")] string token, [FromBody] UserClockInRequest data)
        {
            if (!_user.GetUserIdByToken(token.ReplaceBearer(), out long userId))
            {
                return ApiResultStatus.Fail(ApiResultCodes.PARAMS_FAILED);
            }

            if (data == null || string.IsNullOrWhiteSpace(data.PicUrl))
            {
                return ApiResultStatus.Fail(ApiResultCodes.PARAMS_FAILED);
            }
            if (data.BelongsDate > DateTime.Now.AddDays(1) || data.BelongsDate <= _config.MinDate)
            {
                return ApiResultStatus.Fail(ApiResultCodes.PARAMS_FAILED);
            }
            data.UserCheckInfoId = _userCheckInfo.GetIdByUserIdAndBelongsDate(userId, data.BelongsDate.Date);
            if (!data.UserCheckInfoId.NumberGtZero())
            {
                return ApiResultStatus.Fail(ApiResultCodes.OPERATION_FAILED);
            }
            return ApiResultStatus.Create(_userCheckInfo.UserClockIn(data), ApiResultCodes.SERVER_ERROR);
        }

        /// <summary>
        ///  打下班卡api
        /// </summary>
        [HttpPost]
        [Route("UserClockOut")]
        public ApiResult UserClockOut([FromHeader(Name = "Authorization")] string token, [FromBody] UserClockInRequest data)
        {
            if (!_user.GetUserIdByToken(token.ReplaceBearer(), out long userId))
            {
                return ApiResultStatus.Fail(ApiResultCodes.PARAMS_FAILED);
            }

            if (data == null || string.IsNullOrWhiteSpace(data.PicUrl))
            {
                return ApiResultStatus.Fail(ApiResultCodes.PARAMS_FAILED);
            }
            if (data.BelongsDate > DateTime.Now.AddDays(1) || data.BelongsDate <= _config.MinDate)
            {
                return ApiResultStatus.Fail(ApiResultCodes.PARAMS_FAILED);
            }
            data.UserCheckInfoId = _userCheckInfo.GetIdByUserIdAndBelongsDate(userId, data.BelongsDate.Date);
            if (!data.UserCheckInfoId.NumberGtZero())
            {
                return ApiResultStatus.Fail(ApiResultCodes.OPERATION_FAILED);
            }
            if (!_userCheckInfo.ExistUserClockIn(userId, data.BelongsDate.Date))
            {
                return ApiResultStatus.Fail(ApiResultCodes.PARAMS_FAILED, "请先进行上班打卡，再重试");
            }
            return ApiResultStatus.Create(_userCheckInfo.UserClockOut(data), ApiResultCodes.SERVER_ERROR);
        }

        /// <summary>
        /// 获取所有人打卡记录
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetUserCheckInfoByDay")]
        public ApiResult GetUserCheckInfoByDay(DateTime date)
        {
            string token = Request.GetToken();
            if (!_user.GetUserIdByToken(token, out long userId))
            {
                return ApiResultStatus.Fail(ApiResultCodes.PARAMS_FAILED);
            }
            if (date > DateTime.Now.AddDays(1) || date <= _config.MinDate)
            {
                return ApiResultStatus.Fail(ApiResultCodes.PARAMS_FAILED);
            }
            DateTime startTime = date.Date;
            DateTime endTime = startTime.AddDays(1);
            var datas = _userCheckInfo.GetUserCheckInfoByMonth(userId, startTime, endTime);
            return ApiResultStatus.Success(datas);
        }

        /// <summary>
        /// 查询某个人员当月数据
        /// </summary>
        [HttpGet]
        [Route("GetUserCheckInfoByMonth")]
        public ApiResult GetUserCheckInfoByMonth(DateTime date)
        {
            string token = Request.GetToken();
            if (!_user.GetUserIdByToken(token, out long userId))
            {
                return ApiResultStatus.Fail(ApiResultCodes.PARAMS_FAILED);
            }
            if (date > DateTime.Now.AddDays(1) || date <= _config.MinDate)
            {
                return ApiResultStatus.Fail(ApiResultCodes.PARAMS_FAILED);
            }
            DateTime startTime = new DateTime(date.Year, date.Month, 1);
            DateTime endTime = startTime.AddMonths(1);
            var datas = _userCheckInfo.GetUserCheckInfoByMonth(userId, startTime, endTime);
            return ApiResultStatus.Success(datas);
        }
        
        // 管理员查看所有人员某天打卡记录
        [HttpPost]
        [Route("GetAllUserCheckInfo")]
        public ApiResult GetAllUserCheckInfo([FromBody] PageBo<UserCheckInfoParams> pageBo) 
        {
            DateTime now = DateTime.Now;
            if (pageBo.Param == null) 
            {
                pageBo.Param = new UserCheckInfoParams();
            }
            if (pageBo.Param.StartDate < _config.MinDate) 
            {
                pageBo.Param.StartDate = new DateTime(now.Year, now.Month, 1);
            }
            pageBo.Param.StartDate = pageBo.Param.StartDate.Date;
            if (pageBo.Param.EndDate < _config.MinDate) 
            {
                pageBo.Param.EndDate = new DateTime(now.Year, now.Month, 1).AddMonths(1).AddSeconds(-1);
            }
            pageBo.Param.EndDate = pageBo.Param.EndDate.Date.AddDays(1).AddSeconds(-1);

            var datas = _userCheckInfo.GetAllUserCheckInfo(pageBo);
            return ApiResultStatus.Success(datas);
        }
    } 
}
